package oer.halk.intercept_demo.intercept;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 请求日志
 *
 * @Author zhuhao
 * @Date 2022/1/26 16:20
 * @desc
 */
@Component
@Slf4j
public class LogIntercept implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        beforeRequestLogInfo(request);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    /**
     * 在请求到达业务员处理器之前，记录请求日志
     *
     * @param request
     */
    private void beforeRequestLogInfo(HttpServletRequest request) throws IOException {
        //获取请求方式
        String method = request.getMethod();
        //请求地址
        String requestURI = request.getRequestURI();

        //获取请求参数
        String paramsStr = "";
        if ("POST".equals(method)) {
            //获取post请求参数
            paramsStr = this.getPostParam(request);
        } else if ("GET".equals(method)) {
            //Get方式请求参数
            paramsStr = request.getQueryString();
        }
        String template = "请求方式：%s ；请求地址：%s ；请求参数：%s 。";
        log.info(String.format(template, method, requestURI, paramsStr));
    }

    /**
     * 获取post请求中参数
     *
     * @param request
     * @return
     */
    private String getPostParam(HttpServletRequest request) throws IOException {
//        String body = StreamUtils.copyToString(request.getInputStream(), Charset.forName(request.getCharacterEncoding()));
        String body = StreamUtils.copyToString(new BodyReaderWrapper(request).getInputStream(), Charset.forName(request.getCharacterEncoding()));

        if (ObjectUtils.isEmpty(body)) {
            return "";
        }
        return body;
    }
}
